package a.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;

import java.net.InetSocketAddress;

public class ServerApp {
    private final int port;

    public ServerApp(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup boss = new NioEventLoopGroup(1);//Netty的Reactor线程池，初始化了一个NioEventLoop数组，用来处理I/O操作,如接受新的连接和读/写数据
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();//用于启动NIO服务
            b.group(boss, worker)
                    .channel(NioServerSocketChannel.class) //通过工厂方法实例化一个channel
                    .localAddress(new InetSocketAddress(port))//设置监听端口
                    // 可以添加多个引导，但是只有最后一个会起作用
                    .childHandler(/* 引导 ChannelInitializer */new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            ChannelPipeline pipeline = socketChannel.pipeline();

                            pipeline.addLast(new ServerHandler());

                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new HttpObjectAggregator(65536));
                            pipeline.addLast(new HttpServerChannelHandler());
                        }
                    });

            //绑定服务器，该实例将提供有关IO操作的结果或状态的信息
            ChannelFuture channelFuture= b.bind().sync();
            InetSocketAddress socketAddress = (InetSocketAddress) channelFuture.channel().localAddress();
            System.out.println("[" + socketAddress.getHostName() + "]:" + socketAddress.getPort() + " - " + "开启监听");

            //阻塞操作，closeFuture()开启了一个channel的监听器（这期间channel在进行各项工作），直到链路断开
            channelFuture.channel().closeFuture().sync();
        } finally{
            boss.shutdownGracefully().sync();//关闭EventLoopGroup并释放所有资源，包括所有创建的线程
            worker.shutdownGracefully().sync();
        }
    }
}
